--
-- DE2 (Cyclone-II) Entity for Interactive Project Game
-- Authors:
--      Abdulhamid Ghandour
--      Thomas John
--      Jaime Peretzman
--      Bharadwaj Vellore
--
-- Desc:
--

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity soundcontroller is
  
  port (
    clk        : in  std_logic;
    reset_n    : in  std_logic;
    read       : in  std_logic;
    write      : in  std_logic;
    chipselect : in  std_logic;
    address    : in  unsigned(3 downto 0);
    readdata   : out unsigned(31 downto 0);
    writedata  : in  unsigned(31 downto 0);
    aud_xck    : out std_logic;
    aud_adclrck: out std_logic;
    aud_adcdat : in std_logic;
    aud_daclrck: out std_logic;
    aud_dacdat : out std_logic;
    aud_bclk   : inout std_logic
  );
end soundcontroller;

architecture rtl of soundcontroller is

  type ram_type is array(7 downto 0) of unsigned(31 downto 0);
  signal RAM : ram_type;
  signal ram_address : unsigned(2 downto 0);
  signal counter  : unsigned(31 downto 0);
  signal audio_clock : unsigned(1 downto 0) := "00";
  signal audio_request : std_logic;
  signal reset_ctrl: std_logic := '0';
begin
  ram_address <= address(2 downto 0);

  audio_clk_gen: process (clk)
  begin
    if rising_edge(clk) then
      audio_clock <= audio_clock + "1";
    end if;
  end process audio_clk_gen;

  audio_state_ctrl: process (clk)
  begin
    if rising_edge (clk) then
      if RAM(0)(0) = '1' then
        reset_ctrl <= '1';
        counter <= (others => '0');
        RAM(0)(0) <= '0';
      else
        if counter = 150000 then
          counter <= (others => '0');
          reset_ctrl <= '0';
        else    
          counter <= counter + 1;
        end if;
      end if;
    end if;
  end process audio_state_ctrl;

  aud_xck <= audio_clock(1);

  beeper: entity work.de2_wm8731_audio port map (
    clk => audio_clock(1),
    reset_n => reset_ctrl,
    test_mode => '1',                   -- Output a sine wave
    audio_request => audio_request,
    data => "0000000000000000",
    AUD_ADCLRCK  => aud_adclrck,
    AUD_ADCDAT   => aud_adcdat,
    AUD_DACLRCK  => aud_daclrck,
    AUD_DACDAT   => aud_dacdat,
    AUD_BCLK     => aud_bclk
  );
end rtl;
